//
//  AddImportantViewController.m
//  Utils
//
//  Created by enghou on 2018/6/7.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "AddImportantViewController.h"
#import "XXTextView.h"
#import "ScrollAddImageView.h"
#import "LocalPersistent.h"
#import "NumberChecker.h"
#import <TZImagePickerController.h>
#import "NetWorkerManager.h"
@interface AddImportantViewController ()<ShowImagePicker>

@property (weak, nonatomic) IBOutlet UITextField *importantAreaField;

@property (weak, nonatomic) IBOutlet UITextField *questionField;

@property (weak, nonatomic) IBOutlet UITextField *areaTypeField;

@property (weak, nonatomic) IBOutlet XXTextView *rangeField;

@property (weak, nonatomic) IBOutlet XXTextView *manipulatorMainField;

@property (weak, nonatomic) IBOutlet XXTextView *manipulatorPartnerField;

@property (weak, nonatomic) IBOutlet XXTextView *manipulatorNameField;


@property (weak, nonatomic) IBOutlet XXTextView *manipulatorStablePhoneField;

@property (weak, nonatomic) IBOutlet UITextField *manipulatorPhoneField;

@property (weak, nonatomic) IBOutlet UITextField *timeLimitField;

//破获刑事案件数字
@property (weak, nonatomic) IBOutlet XXTextView *resolveCountField;

//查处治安案件数
@property (weak, nonatomic) IBOutlet XXTextView *businessCountField;

@property (weak, nonatomic) IBOutlet UITextField *manipulatorSuituationField;


@property (weak, nonatomic) IBOutlet UITextField *resultEstimateField;


@property (weak, nonatomic) IBOutlet ScrollAddImageView *filesCollection;


@property(nonatomic,strong)UITextField *dateField;

@property(nonatomic,strong)UIDatePicker *datePicker;
@end

@implementation AddImportantViewController{
#pragma mark - 一些需要被上传的参数
    NSString *problemId;//突出问题ID
    NSString *areaTypeId;//区域类型ID
    NSString *estimateId;//评估效果ID
    NSMutableArray *fileURLs;
    
    NSArray *problemsArray;//治安突出问题集合
    NSArray *relatedAreaTypeArray;//涉及区域类型集合
    NSArray *estimateArray;//效果集合
}

-(instancetype)init{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"ImportantArea" bundle:[NSBundle mainBundle]];
    return [story instantiateViewControllerWithIdentifier:@"AddImportantViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.filesCollection.delegate = self;
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 240)];
    self.datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    self.datePicker.backgroundColor = [UIColor whiteColor];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    self.dateField = [[UITextField alloc]init];
    self.dateField.inputView = self.datePicker;
    self.dateField.inputAccessoryView = [self inputAccessView];
    [self.view addSubview:self.dateField];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)sureAction{
    [self.view endEditing:YES];
    self.timeLimitField.text = [[self.datePicker date]dateLineStrOnlyDay];
}

-(void)cancelAction{
    [self.view endEditing:YES];
}

#pragma mark - ShowPicker
-(void)showPicker{
    NSInteger imagecount = self.filesCollection.source.count;
    if (imagecount < 3) {
        TZImagePickerController *picker = [[TZImagePickerController alloc]initWithMaxImagesCount:3 - imagecount delegate:nil];
        picker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            NSMutableArray *files = [NSMutableArray array];
            for (UIImage *image in photos) {
                MediaItemModel *model = [[MediaItemModel alloc]init];
                model.image = image;
                [files addObject:model];
            }
            [self.filesCollection feedImages:files];
        };
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        [self alertSome:@"最多选3张图片!"];
    }
}

#pragma mark - AddAndEdit

-(NSString *)detailPath{
    return @"/mobile/comprehensiveGovernance/socialSecurity/getSocialSecurityById.action";
}

-(NSDictionary *)detailParam{
    return @{@"id":self.ids};
}

-(void(^)(NSDictionary *))configView{
    void (^config)(NSDictionary *) = ^(NSDictionary *source){
#pragma warning - 等待实现
        NSDictionary *data = source[@"data"];
        self.importantAreaField.text = data[@"securityKeyAreas"];
        NSDictionary *effectEvaluate = data[@"effectEvaluate"];
        self->estimateId = effectEvaluate[@"id"];
        self.resultEstimateField.text = effectEvaluate[@"displayName"];
        NSArray *files = data[@"files"];
        NSMutableArray *filesource = [NSMutableArray array];
        for (NSDictionary *element in files) {
            MediaItemModel *model = [[MediaItemModel alloc]initWithSource:element];
            [filesource addObject:model];
        }
        [self.filesCollection feedImages:filesource];
        self.ids = data[@"id"];
        self.resolveCountField.text = [NSString stringWithFormat:@"%li",[data[@"investigatePunishNumber"] integerValue]];
        self.areaTypeField.text = data[@"involvedType"][@"displayName"];
        self->areaTypeId = data[@"involvedType"][@"id"];
        self.manipulatorNameField.text = data[@"leaderUnitDirector"];
        self.manipulatorPhoneField.text = data[@"leaderUnitDirectorMobileNumber"];
        self.manipulatorStablePhoneField.text = data[@"leaderUnitDirectorTelephone"];
        self.rangeField.text = data[@"relateArea"];
        self.manipulatorMainField.text = data[@"repairLeaderUnit"];
        self.manipulatorPartnerField.text = data[@"repairPartakeUnit"];
        self.manipulatorSuituationField.text = data[@"repairSituation"];
        self.timeLimitField.text = data[@"repairTimelimit"];
        self->problemId = data[@"securityProblems"][@"id"];
        self.questionField.text = data[@"securityProblems"][@"displayName"];
        self.businessCountField.text = [NSString stringWithFormat:@"%li",[data[@"solveNumber"] integerValue]];
    };
    
    return config;
}

-(NSString *)addPath{
    return @"/mobile/comprehensiveGovernance/socialSecurity/addSocialSecurity.action";
}

-(NSDictionary *)searchParameter{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.importantAreaField.text length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请输入治安重点区域"];
            return nil;
        }
    }else{
        [param setObject:self.importantAreaField.text forKey:@"enterpriseVo.securityKeyAreas"];
    }
    
    NSString *orgID = [[LocalPersistent sharedInstance]contentForKey:@"orgId"];
    if (orgID) {
        [param setObject:orgID forKey:@"enterpriseVo.organization.id"];
    }
    if ([problemId length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择治安突出问题"];
            return nil;
        }
    }else{
        [param setObject:problemId forKey:@"enterpriseVo.securityProblems.id"];
    }
    if ([areaTypeId length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择区域类型"];
            return nil;
        }
    }else{
        [param setObject:areaTypeId forKey:@"enterpriseVo.involvedType.id"];
    }
    if ([_rangeField.text length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请填写涉及区域范围"];
            return nil;
        }
    }else{
        [param setObject:_rangeField.text forKey:@"enterpriseVo.relateArea"];
    }
    [param setObject:_manipulatorMainField.text forKey:@"enterpriseVo.repairLeaderUnit"];
    [param setObject:_manipulatorPartnerField.text forKey:@"enterpriseVo.repairPartakeUnit"];
    [param setObject:_manipulatorNameField.text forKey:@"enterpriseVo.leaderUnitDirector"];
    [param setObject:_manipulatorStablePhoneField.text forKey:@"enterpriseVo.leaderUnitDirectorTelephone"];
    if (![NumberChecker validPhone:self.manipulatorPhoneField.text]) {
        if (!self.needParameter) {
            [self alertSome:@"请输入有效的手机号码"];
            return nil;
        }
    }else{
        [param setObject:_manipulatorPhoneField.text forKey:@"enterpriseVo.leaderUnitDirectorMobileNumber"];
    }
    if ([_timeLimitField.text length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择整改时限"];
            return nil;
        }
    }else{
        [param setObject:_timeLimitField.text forKey:@"enterpriseVo.repairTimelimit"];
    }
    [param setObject:self.resolveCountField.text forKey:@"enterpriseVo.solveNumber"];
    [param setObject:self.manipulatorSuituationField.text forKey:@"enterpriseVo.repairSituation"];
    [param setObject:self.businessCountField.text forKey:@"enterpriseVo.investigatePunishNumber"];
    if ([estimateId length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择评估效果!"];
            return nil;
        }
    }else{
        [param setObject:estimateId forKey:@"enterpriseVo.effectEvaluate.id"];
    }
    return param;
}

-(NSDictionary *)addedParameter{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.importantAreaField.text length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请输入治安重点区域"];
            return nil;
        }
    }else{
        [param setObject:self.importantAreaField.text forKey:@"enterprise.securityKeyAreas"];
    }
    
    NSString *orgID = [[LocalPersistent sharedInstance]contentForKey:@"orgId"];
    if (orgID) {
        [param setObject:orgID forKey:@"enterprise.organization.id"];
    }
    if ([problemId length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择治安突出问题"];
            return nil;
        }
    }else{
        [param setObject:problemId forKey:@"enterprise.securityProblems.id"];
    }
    if ([areaTypeId length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择区域类型"];
            return nil;
        }
    }else{
        [param setObject:areaTypeId forKey:@"enterprise.involvedType.id"];
    }
    if ([_rangeField.text length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请填写涉及区域范围"];
            return nil;
        }
    }else{
        [param setObject:_rangeField.text forKey:@"enterprise.relateArea"];
    }
    [param setObject:_manipulatorMainField.text forKey:@"enterprise.repairLeaderUnit"];
    [param setObject:_manipulatorPartnerField.text forKey:@"enterprise.repairPartakeUnit"];
    [param setObject:_manipulatorNameField.text forKey:@"enterprise.leaderUnitDirector"];
    [param setObject:_manipulatorStablePhoneField.text forKey:@"enterprise.leaderUnitDirectorTelephone"];
    if (![NumberChecker validPhone:self.manipulatorPhoneField.text]) {
        if (!self.needParameter) {
            [self alertSome:@"请输入有效的手机号码"];
            return nil;
        }
    }else{
        [param setObject:_manipulatorPhoneField.text forKey:@"enterprise.leaderUnitDirectorMobileNumber"];
    }
    if ([_timeLimitField.text length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择整改时限"];
            return nil;
        }
    }else{
        [param setObject:_timeLimitField.text forKey:@"enterprise.repairTimelimit"];
    }
    [param setObject:self.resolveCountField.text forKey:@"enterprise.solveNumber"];
    [param setObject:self.manipulatorSuituationField.text forKey:@"enterprise.repairSituation"];
    [param setObject:self.businessCountField.text forKey:@"enterprise.investigatePunishNumber"];
    if ([estimateId length] == 0) {
        if (!self.needParameter) {
            [self alertSome:@"请选择评估效果!"];
            return nil;
        }
    }else{
        [param setObject:estimateId forKey:@"enterprise.effectEvaluate.id"];
    }
    if (fileURLs) {
        NSString *urls = [fileURLs componentsJoinedByString:@","];
        [param setObject:urls forKey:@"filePaths"];
    }
    return param;
}

-(void)uploadFiles:(NSArray <NSData *>*)files successBlock:(void(^)(NSArray <FileItemModel *>*))suc{
    [self beginLoading];
    [[NetWorkerManager sharedInstance]uploadImageWithPath:kUploadFilePath parameter:nil files:files fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
        [self endLoading];
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[FileItemModel class]];
        if (model.success) {
            if (suc) {
                suc(model.list);
            }
        }else{
            [self alertSome:model.msg];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)addRecord{
    if (self.filesCollection.source.count > 0) {
        //线上船图片
        NSMutableArray *datas = [NSMutableArray array];
        for (MediaItemModel *model in self.filesCollection.source) {
            NSData *data = UIImageJPEGRepresentation(model.image, 0.2);
            [datas addObject:data];
        }
        fileURLs = [NSMutableArray array];
        [self uploadFiles:datas successBlock:^(NSArray<FileItemModel *> *list) {
            for (FileItemModel *model in list) {
                [self->fileURLs addObject:model.path];
            }
            [super addRecord];
            self->fileURLs = nil;
        }];
    }else{
        [super addRecord];
        fileURLs = nil;
    }
}

-(NSString *)updatePath{
    return @"/mobile/comprehensiveGovernance/socialSecurity/updateSocialSecurity.action";
}

-(NSDictionary *)updateParameter{
    NSMutableDictionary *param = [[self addedParameter]mutableCopy];
    NSMutableArray *deletedFiles = [NSMutableArray array];
    [self.filesCollection.deletedFiles enumerateObjectsUsingBlock:^(MediaItemModel * obj, NSUInteger idx, BOOL * stop) {
        [deletedFiles addObject:obj.ids];
    }];
    NSString *deletedFileString = [NSString stringWithFormat:@"[%@]",[deletedFiles componentsJoinedByString:@","]];
    if (deletedFileString) {
        [param setObject:deletedFileString forKey:@"removeIds"];
    }
    return param;
}

-(NSString *)delPath{
    return @"/mobile/comprehensiveGovernance/socialSecurity/deleteSocialSecurityById.action";
}

-(NSDictionary *)delParameter{
    return @{@"id":self.ids};
}

-(NSString *)refresh_not_name{
    return @"RefreshImportantList";
}

#pragma mark -  UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //突出治安问题
    //涉及区域类型
    //效果评估
    if (indexPath.row == 1) {
        [self commonAlertWithContent:@"治安突出问题" choosenBlock:^(PropertyDictItemModel *model) {
            self->problemId = model.ids;
            self.questionField.text = model.displayName;
        } getList:^(NSArray *array) {
            self->problemsArray = array;
        }];
    }else if (indexPath.row == 2){
        [self commonAlertWithContent:@"涉及区域类型" choosenBlock:^(PropertyDictItemModel *model) {
            self->areaTypeId = model.ids;
            self.areaTypeField.text = model.displayName;
        } getList:^(NSArray *array) {
            self->relatedAreaTypeArray = array;
        }];
    }else if (indexPath.row == 9){
        [self.dateField becomeFirstResponder];
    }else if (indexPath.row == 13){
        [self commonAlertWithContent:@"效果评估" choosenBlock:^(PropertyDictItemModel *model) {
            self->estimateId = model.ids;
            self.resultEstimateField.text = model.displayName;
        } getList:^(NSArray *array) {
            self->estimateArray = array;
        }];
    }
}

@end
